//
//  TQVedioHelper.swift
//  TQMedia
//
//  Created by XieLB on 2018/9/27.
//  Copyright © 2018年 XieLB. All rights reserved.
//

import UIKit

typealias JMDicCloser = ((Dictionary<String, Any>) -> ())

typealias JMNoneCloser = (()->())

class TQVedioHelper: NSObject {
    // MARK:- 单例
    static let instance = TQVedioHelper()
    static func share() -> TQVedioHelper {
        return instance
    }
    
    var ijkPlayerView: IJKPlayerView?
    
    var downloaders: [JMDownloader] = [JMDownloader]()
    
    var urls: [String] = [String]() // 用于存储当前点击过的url,方便查找对就近的url 获取对应的 downloaders 中 对应的 downloader,以便删除
    
    /// 播放视频
    func playVedio(_ params: Dictionary<String, Any>) {
        
        guard let frame = params["frame"] as? CGRect else {
            return
        }
        guard let closer = (params["closer"] as? ((UIView) -> ())) else {
            return
        }
        ijkPlayerView = IJKPlayerView.init(frame: frame)
        ijkPlayerView!.delegate = self
        let fileName = "http://statics.aichezaixian.com/351609080199717_1_2018_08_10_10_31_43".md5 + ".mp4"
        let fileURL = kVideoDireURL.appendingPathComponent(fileName)
        ijkPlayerView!.playLocalVideo(fileURL, currentPlaybackTime: 0, isAutoPlay: true)
        closer(ijkPlayerView!)
    }
    
    /// 停止播放视频
    func stopVedio(_ params: Dictionary<String, Any>) {
        ijkPlayerView?.delegate = nil
        ijkPlayerView?.isHidden = true
        ijkPlayerView?.pausePlay(nil)
        ijkPlayerView?.removeFromSuperview()
    }
    
    /// 下载视频接口
    func downloadVedio(_ params: Dictionary<String, Any>) {
        print("downloadVedio")
        guard let downloadUrl = (params["downloadUrl"] as? String) else {
            return
        }
        let closer = (params["closer"] as? JMDicCloser) ??  {_ in }
        self.startDownloader(downloadUrl, closer)
    }
    
    /// 暂停下载视频接口
    func pauseDownloadVedio(_ params: Dictionary<String, Any>) {
        print("pauseDownloadVedio")
        guard let downloadUrl = (params["downloadUrl"] as? String) else {
            return
        }
        self.pauseDownloader(downloadUrl)
    }
    
    /// 暂停所有下载视频接口
    func pauseAllDownloadVedio(_ params: Dictionary<String, Any>) {
        print("pauseAllDownloadVedio")
        let isResfreshCancleDownload = (params["isResfreshCancleDownload"] as? Bool) ?? false
        let closer = (params["closer"] as? JMNoneCloser) ??  { }
        self.pauseAllDownload(isResfreshCancleDownload, closer)
    }
}

extension TQVedioHelper {
    
    // MARK:- 开始下载
    func startDownloader(_ url: String, _ progressCallback: @escaping JMDicCloser) {
        
        // Download
        let downloader: JMDownloader
        
        // 区分是否为已创建downloader
        if let index = urls.index(of: url) {
            downloader = downloaders[index]
            
        } else {
            // 创建
            downloader = JMDownloader()
            // 存入数组中
            downloaders.append(downloader)
            urls.append(url)
        }
        
        //  [weak self]
        downloader.startDownLoad(url) { downloadItem in
            // 传出对应进度
            progressCallback(downloadItem)
        }
    }
    
    func startDownloadWithItem(_ downloadItem: Dictionary<String, Any>, _ progressCallback: @escaping JMDicCloser) {
        
        guard let url = downloadItem["url"] as? String else {
            return
        }
        
        // Download
        let downloader: JMDownloader
        
        // 区分是否为已创建downloader
        if let index = urls.index(of: url) {
            downloader = downloaders[index]
            
        } else {
            // 创建
            downloader = JMDownloader()
            
            // 存入数组中
            downloaders.append(downloader)
            urls.append(url)
        }
        
        downloader.startDownLoadWithItem(downloadItem) { downloadItem in
            // 传出对应进度
            progressCallback(downloadItem)
        }
    }
    
    // MARK:- 暂停下载
    func pauseDownloader(_ url: String) {
        
        if let index = urls.index(of: url) {
            let downloader = downloaders[index]
            downloader.isResfreshCancleDownload = false
            downloader.stopDownload()
        }
    }
    
    // 暂停全部下载
    func pauseAllDownload(_ isResfreshCancleDownload: Bool, _ completed: JMNoneCloser?) {
        
        for downloader in downloaders {
            downloader.isResfreshCancleDownload = isResfreshCancleDownload
            downloader.stopDownload()
        }

        completed?()
    }
}

extension TQVedioHelper: VideoPlayViewDelegate {
    
    func videoPlayViewTouchesBegan(_ isHidden: Bool) {
        
        //        isTapCallback?(isHidden)
        //        ijkPlayerView.playerToolView.isHidden = isHidden
        //        toolView.isHidden = model.ext == ".3gp" || isHidden
    }
    
    func videoPlayViewOrientation(_ isFull: Bool) {
        //        print("点击了全屏按钮：\(isFull)")
        //
        //        tapCallback?(self,isFull)
    }
}
